package com.yu.markdowntohtml.controller;

import com.yu.markdowntohtml.utils.FileUtil;
import com.yu.markdowntohtml.utils.MarkdownUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author lloverain
 * @Data 2021-12-06 16:50
 **/
@Controller
public class DocumentController {
    @RequestMapping("/")
    public String toTest(Model model) {
        String text = FileUtil.readByLines("C:\\config\\文档.md");
        String html = MarkdownUtils.markdownToHtmlExtensions(text);
        model.addAttribute("markdown", html);
        return "markdown";
    }

    @RequestMapping("/download")
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        OutputStream toClient = null;
        ByteArrayOutputStream baos = null;
        InputStream fis = null;
        try {
            File file = new File("C:\\config\\文档.md");
            fis = new BufferedInputStream(new FileInputStream(file));
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, read);
            }
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
            response.addHeader("Content-Length ", file.length() + "");
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(baos.toByteArray());
            toClient.flush();
            baos.flush();

        } catch (Exception e) {

        } finally {
            try {
                if (toClient != null) {
                    toClient.close();
                }
                if (baos != null) {
                    baos.close();
                }

                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "下载失败";
    }
}
